<template>
  <el-drawer v-model="formCtrl.isDrawerOpen" class="cupk2-data-form" :append-to-body="true" :with-header="false"
    size="500px">
    <div class="title">{{ currentFormType.type.title }}</div>
    <el-form v-loading="isLoading" label-width="auto" ref="ruleFormRef" :disabled="!formCtrl.isAbledForm">
      <File_upload_box :multiple="true" :error-handle="errorHandle" :success-handle="successHandle">
      </File_upload_box>
      <el-switch v-if="formCtrl.isShowRetain" v-model="isRetainForm" inactive-text="提交后保留表单" />
    </el-form>
  </el-drawer>
</template>
<script lang="ts" setup>

import { inject, onMounted, reactive, ref } from 'vue';
import File_upload_box from './file_upload_box.vue';
import { MittKeysEnum } from '../utils/mittKeys'
import { getCreatType, getViewType, type FormParam } from '@/types/commons/FormType';
import type { Emitter, EventType } from 'mitt';
import cupkFormUtils from '@/hook/cupkFormUtils';
import { PageEvent } from '@/types/commons/PageEvent';
import notice from '@/components/msg/CupkNotice';
const eventBus = inject('eventBus') as Emitter<Record<EventType, unknown>>;
const ruleFormRef = ref()
const isLoading = ref(false);
const currentFormType = reactive<FormParam>({ type: getViewType(), id: '', data: {} });
const isRetainForm = ref(false);

const formCtrl = reactive({
  isShowRetain: true,
  isShowSubmit: true,
  isDrawerOpen: false,
  isAbledForm: false,
  isShowReset: true
});

/**
 * 打开或关闭表单窗口
 * @param isOpen
 * @param formType
 */
const drawerWinOpen = (isOpen: boolean, formParam?: FormParam) => {
  if (!isOpen) {
    formCtrl.isDrawerOpen = isOpen;
  } else {
    if (formParam?.type.key !== currentFormType?.type.key) {
      ruleFormRef.value?.resetFields();
    }
    Object.assign(currentFormType, formParam);
    if (formParam?.type.key == getCreatType().key) {
      initCreatForm(formParam);
    }
  }
};
/**
 * 初始化创建窗口
 */
const initCreatForm = (formParam: FormParam) => {
  cupkFormUtils.initFormCtrl(getCreatType(), formCtrl);
  if (formParam) {

  }
}

const errorHandle = (msg: Error) => {
  notice.byError(msg.message);
}
const successHandle = () => {
  notice.bySuccess("上传成功!");
  eventBus.emit(PageEvent.data_do_query);
  if (isRetainForm.value) {
  } else {
    formCtrl.isDrawerOpen = false;
  }
}


onMounted(() => {
  eventBus.on(MittKeysEnum.openUploadForm, (paras) => {
    drawerWinOpen((paras as { isOpen: boolean }).isOpen, (paras as { type: FormParam }).type);
  })
});
</script>
